<template>
  <div class="change-password-container" :class="theme">
    <div class="password-card">
      <div class="card-header">
        <h2><i class="fas fa-key"></i> 修改密码</h2>
        <button class="theme-toggle" @click="toggleTheme" :title="theme === 'light' ? '切换深色模式' : '切换浅色模式'">
          <i class="fas" :class="themeIcon"></i>
        </button>
      </div>

      <div class="card-body">
        <form @submit.prevent="handleSubmit">
          <div class="form-group" :class="{ 'has-error': errors.oldPassword }">
            <label for="oldPassword">当前密码</label>
            <div class="input-with-icon">
              <i class="fas fa-lock"></i>
              <input id="oldPassword" v-model="form.oldPassword" :type="showOldPassword ? 'text' : 'password'"
                placeholder="请输入当前密码" @blur="validateField('oldPassword')" />
              <button type="button" class="toggle-password" @click="showOldPassword = !showOldPassword">
                <i class="fas" :class="showOldPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
              </button>
            </div>
            <div class="error-message" v-if="errors.oldPassword">{{ errors.oldPassword }}</div>
          </div>

          <div class="form-group" :class="{ 'has-error': errors.newPassword }">
            <label for="newPassword">新密码</label>
            <div class="input-with-icon">
              <i class="fas fa-lock"></i>
              <input id="newPassword" v-model="form.newPassword" :type="showNewPassword ? 'text' : 'password'"
                placeholder="请输入新密码 (至少8位)" @blur="validateField('newPassword')" @input="checkPasswordStrength" />
              <button type="button" class="toggle-password" @click="showNewPassword = !showNewPassword">
                <i class="fas" :class="showNewPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
              </button>
            </div>
            <div class="password-strength" v-if="form.newPassword">
              <div class="strength-bar" :class="strengthClass"></div>
              <span class="strength-text">{{ strengthText }}</span>
            </div>
            <div class="error-message" v-if="errors.newPassword">{{ errors.newPassword }}</div>
          </div>

          <div class="form-group" :class="{ 'has-error': errors.confirmPassword }">
            <label for="confirmPassword">确认新密码</label>
            <div class="input-with-icon">
              <i class="fas fa-lock"></i>
              <input id="confirmPassword" v-model="form.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'" placeholder="请再次输入新密码"
                @blur="validateField('confirmPassword')" />
              <button type="button" class="toggle-password" @click="showConfirmPassword = !showConfirmPassword">
                <i class="fas" :class="showConfirmPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
              </button>
            </div>
            <div class="error-message" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</div>
          </div>

          <div class="form-actions">
            <button type="button" class="btn btn-secondary" @click="handleCancel">
              取消
            </button>
            <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
              <span v-if="!isSubmitting">确认修改</span>
              <span v-else class="loading">
                <i class="fas fa-spinner fa-spin"></i> 处理中...
              </span>
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 修改成功提示 -->
    <div v-if="showSuccessModal" class="modal-overlay">
      <div class="modal-content">
        <div class="modal-icon success">
          <i class="fas fa-check-circle"></i>
        </div>
        <h3>密码修改成功</h3>
        <p>您的密码已成功更新，请使用新密码登录。</p>
        <button class="btn btn-confirm" @click="handleSuccessConfirm">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, inject } from 'vue';
import { useRouter } from 'vue-router';
import { changePasswordApi } from '../../api/authService.js'
import { LogoutUpdateLog } from "../../api/authService.js";
const userId = localStorage.getItem("userId");
// 主题功能
const theme = inject("theme", ref('light'));
const toggleTheme = () => {
  theme.value = theme.value === 'light' ? 'dark' : 'light';
};

const themeIcon = computed(() => theme.value === 'light' ? 'fa-moon' : 'fa-sun');

const router = useRouter();

// 表单数据
const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单状态
const showOldPassword = ref(false);
const showNewPassword = ref(false);
const showConfirmPassword = ref(false);
const isSubmitting = ref(false);
const showSuccessModal = ref(false);

// 密码强度
const passwordStrength = ref(0);
const strengthText = ref('');
const strengthClass = ref('');

// 错误信息
const errors = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 验证规则
const validateRules = {
  oldPassword: (value) => {
    if (!value) return '请输入当前密码';
    if (value.length < 6) return '密码长度至少6位';
    return '';
  },
  newPassword: (value) => {
    if (!value) return '请输入新密码';
    if (value.length < 8) return '密码长度至少8位';
    if (value === form.value.oldPassword) return '新密码不能与旧密码相同';
    return '';
  },
  confirmPassword: (value) => {
    if (!value) return '请确认新密码';
    if (value !== form.value.newPassword) return '两次输入的密码不一致';
    return '';
  }
};

// 验证单个字段
const validateField = (field) => {
  errors.value[field] = validateRules[field](form.value[field]);
};

// 验证整个表单
const validateForm = () => {
  let isValid = true;
  Object.keys(form.value).forEach((key) => {
    errors.value[key] = validateRules[key](form.value[key]);
    if (errors.value[key]) isValid = false;
  });
  return isValid;
};

// 检查密码强度
const checkPasswordStrength = () => {
  const password = form.value.newPassword;
  if (!password) {
    passwordStrength.value = 0;
    return;
  }

  // 简单密码强度计算
  let strength = 0;
  if (password.length >= 8) strength += 1;
  if (/[A-Z]/.test(password)) strength += 1;
  if (/[0-9]/.test(password)) strength += 1;
  if (/[^A-Za-z0-9]/.test(password)) strength += 1;

  passwordStrength.value = strength;

  // 设置强度文本和样式
  switch (strength) {
    case 0:
    case 1:
      strengthText.value = '弱';
      strengthClass.value = 'weak';
      break;
    case 2:
      strengthText.value = '中等';
      strengthClass.value = 'medium';
      break;
    case 3:
      strengthText.value = '强';
      strengthClass.value = 'strong';
      break;
    case 4:
      strengthText.value = '非常强';
      strengthClass.value = 'very-strong';
      break;
  }
};
// 修改密码的提交逻辑
const handleSubmit = async () => {
  if (!validateForm()) return;  // 表单验证，确保数据合法

  isSubmitting.value = true;  // 设置提交状态为 true，表示正在提交中

  try {
    // 调用修改密码 API
    const response = await changePassword(userId, form.value.oldPassword, form.value.newPassword);
    console.log(response, 'assacascascascascascascas');
    // 如果返回成功，显示成功提示
    if (response) {
      showSuccessModal.value = true;  // 显示成功模态框
    } else {
      // 处理失败情况，可以弹出错误提示
      console.error(response);
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    // 这里可以设置错误提示，比如弹出模态框或者显示错误信息
  } finally {
    isSubmitting.value = false;  // 提交完成后，设置提交状态为 false
  }
};

const logout = () => {
  // LogoutUpdateLog()
  if (loadGetUserData()) {
    localStorage.removeItem('token');
    router.push('/login');
  }
};

const loadGetUserData = async () => {
  try {
    const res = await LogoutUpdateLog(userId);
    console.log(res, '获取用户数据');
    if (res) {

      console.log(res);
    } else {
      ElMessage.error(res.message || "退出失败");
    }
  } catch (error) {
    ElMessage.error("获取失败: ");
  } finally {
    // loading.value = false;
  }
};

// 取消修改
const handleCancel = () => {
  router.go(-1); // 返回上一页
};

// 成功确认
const handleSuccessConfirm = () => {
  // console.log();

  showSuccessModal.value = false;
  logout()
  // 跳转到登录页
};

const changePassword = async (userId, oldPassword, newPassword) => {
  try {
    const response = await changePasswordApi(userId, oldPassword, newPassword);
    if (response) {

      console.log('修改密码成功:', response);
      return true;
    } else {

      console.error('修改密码失败:', response.message);
      return false;
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    return false;
  }
}

</script>

<style scoped>
.change-password-container {
  --bg-color: #f8f9fa;
  --text-color: #333;
  --primary-color: #4361ee;
  --primary-hover: #3a56d8;
  --secondary-color: #6c757d;
  --secondary-hover: #5a6268;
  --border-color: #e1e4e8;
  --card-bg: #fff;
  --hover-bg: #f1f3f5;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  --error-color: #dc3545;
  --success-color: #28a745;
  --warning-color: #ffc107;
  --weak-color: #dc3545;
  --medium-color: #fd7e14;
  --strong-color: #28a745;
  --very-strong-color: #20c997;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: all 0.3s ease;
}

.change-password-container.dark {
  --bg-color: #1a1a1a;
  --text-color: #e0e0e0;
  --primary-color: #4895ef;
  --primary-hover: #3a7bd5;
  --secondary-color: #8e8e8e;
  --secondary-hover: #7a7a7a;
  --border-color: #333;
  --card-bg: #2d2d2d;
  --hover-bg: #383838;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.password-card {
  width: 100%;
  max-width: 500px;
  background-color: var(--card-bg);
  border-radius: 10px;
  box-shadow: var(--shadow);
  overflow: hidden;
}

.card-header {
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.theme-toggle {
  background: none;
  border: none;
  color: var(--secondary-color);
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 50%;
  transition: all 0.2s;
}

.theme-toggle:hover {
  color: var(--primary-color);
  background-color: var(--hover-bg);
}

.card-body {
  padding: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.input-with-icon {
  position: relative;
  display: flex;
  align-items: center;
}

.input-with-icon i:first-child {
  position: absolute;
  left: 1rem;
  color: var(--secondary-color);
}

.input-with-icon input {
  width: 100%;
  padding: 0.75rem 1rem 0.75rem 3rem;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 1rem;
  background-color: var(--card-bg);
  color: var(--text-color);
  transition: border-color 0.2s;
}

.input-with-icon input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
}

.toggle-password {
  position: absolute;
  right: 1rem;
  background: none;
  border: none;
  color: var(--secondary-color);
  cursor: pointer;
  padding: 0.5rem;
}

.toggle-password:hover {
  color: var(--primary-color);
}

.error-message {
  margin-top: 0.5rem;
  color: var(--error-color);
  font-size: 0.85rem;
}

.password-strength {
  margin-top: 0.5rem;
  display: flex;
  align-items: center;
  gap: 0.8rem;
}

.strength-bar {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  background-color: var(--border-color);
  overflow: hidden;
  position: relative;
}

.strength-bar::after {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 0;
  transition: width 0.3s ease;
}

.strength-bar.weak::after {
  width: 25%;
  background-color: var(--weak-color);
}

.strength-bar.medium::after {
  width: 50%;
  background-color: var(--medium-color);
}

.strength-bar.strong::after {
  width: 75%;
  background-color: var(--strong-color);
}

.strength-bar.very-strong::after {
  width: 100%;
  background-color: var(--very-strong-color);
}

.strength-text {
  font-size: 0.85rem;
  color: var(--secondary-color);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.btn {
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  border: none;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover {
  background-color: var(--primary-hover);
}

.btn-primary:disabled {
  background-color: var(--secondary-color);
  cursor: not-allowed;
  opacity: 0.7;
}

.btn-secondary {
  background-color: var(--secondary-color);
  color: white;
}

.btn-secondary:hover {
  background-color: var(--secondary-hover);
}

.loading i {
  margin-right: 0.5rem;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: var(--card-bg);
  border-radius: 10px;
  width: 90%;
  max-width: 400px;
  padding: 2rem;
  text-align: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.modal-icon {
  font-size: 3rem;
  margin-bottom: 1.5rem;
}

.modal-icon.success {
  color: var(--success-color);
}

.modal-content h3 {
  margin: 0 0 1rem;
  font-size: 1.5rem;
}

.modal-content p {
  margin: 0 0 2rem;
  color: var(--secondary-color);
}

.btn-confirm {
  width: 100%;
  background-color: var(--primary-color);
  color: white;
}

.btn-confirm:hover {
  background-color: var(--primary-hover);
}

/* 响应式调整 */
@media (max-width: 576px) {
  .change-password-container {
    padding: 1rem;
  }

  .card-body {
    padding: 1.5rem;
  }

  .form-actions {
    flex-direction: column-reverse;
  }

  .btn {
    width: 100%;
  }
}
</style>